<?php
set_time_limit(600);
error_reporting(E_ALL);
if (!isset($_POST['action']) || !isset($_POST['code'])){
    die(json_encode(['code' => 1, 'msg' => 'param required']));
}

header("Content-Type: application/json;");

// run go code
function run(string $code){
    $fileName = __DIR__.'/'."tmp/goplayground_".sha1(microtime(true)).".go";
    $f = fopen($fileName, 'w+');
    fwrite($f, $code);
    fclose($f);
    exec("/usr/local/go/bin/go run ".$fileName, $res);
    $res = str_replace("\n", "<br>", $res);
    unlink($fileName);
    exit(json_encode(['code' => 0, 'msg' => 'ok', 'res' => $res, 'debug' => "go run ".$fileName]));
}

// format go code
function format($code){
    $fileName = __DIR__.'/'."tmp/goplayground_".sha1(microtime(true)).".go";
    $f = fopen($fileName, 'w+');
    fwrite($f, $code);
    fclose($f);
    exec("/usr/local/go/bin/go fmt ".$fileName, $err);
    $res = file_get_contents($fileName);
    unlink($fileName);
    exit(json_encode(['code' => 0, 'msg' => 'ok', 'res' => $res, 'err' => $err, 'debug' => "go fmt ".$fileName]));
}

$requestAction = $_POST['action'];
$requestCode = $_POST['code'];

switch ($requestAction){
    case "run":
        run($requestCode);
        break;
    case "format":
        format($requestCode);
        break;
}

exit(json_encode(['code' => 1, 'msg' => 'No Action Found']));
